const db_JQL = uniCloud.databaseForJQL();
const { getQuarter, getQuarterStartEndTimestamp } = require('../../common/time');
module.exports = async function(options = {}) {
	// 	characterId: "601528360006385664"
	// ==============完成==============
	// cnAccuracy: 87.5
	// cnAccuracyHistory: [{statisticTime: 1718294400000, dataValue: 0}, {statisticTime: 1718380800000, dataValue: 0},…]

	// cnWpm: 67.5
	// cnWpmExceedValue: 86.44
	// cnWpmHistory: [{statisticTime: 1718294400000, dataValue: 0}, {statisticTime: 1718380800000, dataValue: 0},…]
	// ==============完成==============

	// ==============完成==============
	// correctWpm: 60.39
	// correctWpmExceedValue: 88.27
	// correctWpmHistory: [{statisticTime: 1718294400000, dataValue: 0}, {statisticTime: 1718380800000, dataValue: 0},…]
	// ==============完成==============

	// enAccuracy: 0
	// enAccuracyHistory: [{statisticTime: 1718294400000, dataValue: 0}, {statisticTime: 1718380800000, dataValue: 0},…]
	// enWpm: 0
	// enWpmHistory: [{statisticTime: 1718294400000, dataValue: 0}, {statisticTime: 1718380800000, dataValue: 0},…]


	// ==============完成==============
	// kpm: 440.58
	// kpmExceedValue: 99.52
	// kpmHistory: [{statisticTime: 1718294400000, dataValue: 0}, {statisticTime: 1718380800000, dataValue: 0},…]
	// ==============完成==============

	const { characterId, startTime, endTime } = options;
	const token = this.getUniIdToken();
	const timeResult = getQuarterStartEndTimestamp(getQuarter().year, getQuarter().quarter);
	if (!token) {
		throw new Error('非法访问');
	}
	if (!characterId || !startTime || !endTime) {
		throw new Error('缺少参数');
	}
	if (startTime < timeResult.start) {
		throw new Error('查询开始时间戳不属于该季度！');
	}
	if (timeResult.end < endTime) {
		throw new Error('查询结束时间戳不属于该季度！');
	}
	const result = {
		successWpm: 0, //正确打字速度
		successWpmExceedValue: 0, //正确打字速度超越人数百分比
		kpm: 0, //键盘速度
		kpmExceedValue: 0, //键盘速度超越人数百分比

		cnAccuracy: 0, //中文正确率（不包括按键正确率）
		cnAccuracyExceedValue: 0,
		cnWpm: 0, //中文打字速度
		cnWpmExceedValue: 0,

		enAccuracy: 0, //英文正确率（不包括按键正确率）
		enAccuracyExceedValue: 0,
		enWpm: 0, //英文打字速度
		enWpmExceedValue: 0
	};
	const collection = db_JQL.collection('a-dz-complete-stats-list');
	const where = { createTime: db_JQL.command.gte(startTime).and(db_JQL.command.lte(endTime)) };
	const [totalDataRes, totalDataDatesRes, cnDataRes, cnDataDatesRes, enDataRes, enDataDatesRes] = await Promise.all([
		collection
		// ======获取kpm successWpm 综合数据 start======
		.where({ ...where })
		.groupBy('characterId')
		.groupField('avg(successWpm) as successWpm,avg(kpm) as kpm')
		.get(),
		collection
		.where({ characterId, ...where })
		.groupBy('dateToString(add(new Date(0),createTime),"%Y-%m-%d","+0800") as date')
		.groupField('avg(successWpm) as successWpm,avg(kpm) as kpm')
		.get(),
		// ======获取kpm successWpm 综合数据 end======

		// ======获取cnWpm cnAccuracy 相关数据 start======
		collection
		.where({ ...where, language: 'CN' })
		.groupBy('characterId')
		.groupField('avg(accuracyWord) as accuracy,avg(wpm) as wpm')
		.get(),
		collection
		.where({ characterId, ...where, language: 'CN' })
		.groupBy('dateToString(add(new Date(0),createTime),"%Y-%m-%d","+0800") as date')
		.groupField('avg(accuracyWord) as accuracy,avg(wpm) as wpm')
		.get(),
		// ======获取cnWpm cnAccuracy 相关数据 end======

		// ======获取enWpm enAccuracy 相关数据 start======
		collection
		.where({ ...where, language: 'EN' })
		.groupBy('characterId')
		.groupField('avg(accuracyKey) as accuracy,avg(wpm) as wpm')
		.get(),
		collection
		.where({ characterId, ...where, language: 'EN' })
		.groupBy('dateToString(add(new Date(0),createTime),"%Y-%m-%d","+0800") as date')
		.groupField('avg(accuracyKey) as accuracy,avg(wpm) as wpm')
		.get(),
		// ======获取enWpm enAccuracy 相关数据 end======
	])
	// ======获取kpm successWpm 综合数据 start======
	const totalDataFind = totalDataRes.data.find(item => item.characterId === characterId);
	if (totalDataFind) {
		const successWpmExceedLen = totalDataRes.data.filter(item => item.successWpm < totalDataFind.successWpm).length;
		const kpmExceedLen = totalDataRes.data.filter(item => item.successWpm < totalDataFind.successWpm).length;
		const successWpmExceedValue = (successWpmExceedLen / totalDataRes.data.length) * 100;
		const kpmExceedValue = (kpmExceedLen / totalDataRes.data.length) * 100;
		result.successWpmExceedValue = Number(successWpmExceedValue.toFixed(2));
		result.kpmExceedValue = Number(kpmExceedValue.toFixed(2));
		result.successWpm = Math.round(totalDataFind.successWpm);
		result.kpm = Math.round(totalDataFind.kpm);
	}
	if (totalDataDatesRes.data.length) {
		result.successWpmHistory = totalDataDatesRes.data.map(item => {
			return {
				date: item.date,
				value: item.successWpm
			}
		})
		result.kpmHistory = totalDataDatesRes.data.map(item => {
			return {
				date: item.date,
				value: item.kpm
			}
		})
	}
	// ======获取kpm successWpm 综合数据 end======

	// ======获取cnWpm cnAccuracy 相关数据 start======
	const cnDataResFind = cnDataRes.data.find(item => item.characterId === characterId);
	if (cnDataResFind) {
		const cnWpmExceedLen = cnDataRes.data.filter(item => item.wpm < cnDataResFind.wpm).length;
		const cnAccuracyExceedLen = cnDataRes.data.filter(item => item.accuracy < cnDataResFind.accuracy).length;
		const cnWpmExceedValue = (cnWpmExceedLen / cnDataRes.data.length) * 100;
		const cnAccuracyExceedValue = (cnAccuracyExceedLen / cnDataRes.data.length) * 100;
		result.cnWpmExceedValue = Number(cnWpmExceedValue.toFixed(2));
		result.cnAccuracyExceedValue = Number(cnAccuracyExceedValue.toFixed(2));
		result.cnWpm = Math.round(cnDataResFind.wpm);
		result.cnAccuracy = Math.round(cnDataResFind.accuracy);
	}
	if (cnDataDatesRes.data.length) {
		result.cnWpmHistory = cnDataDatesRes.data.map(item => {
			return {
				date: item.date,
				value: item.wpm
			}
		})
		result.cnAccuracyHistory = cnDataDatesRes.data.map(item => {
			return {
				date: item.date,
				value: item.accuracy
			}
		})
	}
	// ======获取cnWpm cnAccuracy 相关数据 end======

	// ======获取enWpm enAccuracy 相关数据 start======
	const enDataResFind = enDataRes.data.find(item => item.characterId === characterId);
	if (enDataResFind) {
		const enWpmExceedLen = enDataRes.data.filter(item => item.wpm < enDataResFind.wpm).length;
		const enAccuracyExceedLen = enDataRes.data.filter(item => item.accuracy < enDataResFind.accuracy).length;
		const enWpmExceedValue = (enWpmExceedLen / enDataRes.data.length) * 100;
		const enAccuracyExceedValue = (enAccuracyExceedLen / enDataRes.data.length) * 100;
		result.enWpmExceedValue = Number(enWpmExceedValue.toFixed(2));
		result.enAccuracyExceedValue = Number(enAccuracyExceedValue.toFixed(2));
		result.enWpm = Math.round(enDataResFind.wpm);
		result.enAccuracy = Math.round(enDataResFind.accuracy);
	}
	if (enDataDatesRes.data.length) {
		result.enWpmHistory = enDataDatesRes.data.map(item => {
			return {
				date: item.date,
				value: item.wpm
			}
		})
		result.enAccuracyHistory = enDataDatesRes.data.map(item => {
			return {
				date: item.date,
				value: item.accuracy
			}
		})
	}
	// ======获取enWpm enAccuracy 相关数据 end======

	return {
		code: 0,
		data: result,
		msg: '获取成功'
	}
}